import React, { useEffect, useRef } from 'react';
import * as THREE from 'three';
export default function index() {
  const mountRef = useRef(null);
  useEffect(() => {
    const scene = new THREE.Scene();

    const camera = new THREE.PerspectiveCamera(
      75,
      window.innerWidth / window.innerHeight,
      1,
      1000
    );
    camera.position.z = 5;
    camera.position.x = 1;
    camera.position.y = 1;
    scene.add(camera);

    const boxGeometry = new THREE.BoxGeometry(1, 1, 1);
    const boxMeterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
    const boxMesh = new THREE.Mesh(boxGeometry, boxMeterial);
    scene.add(boxMesh);

    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    mountRef.current.appendChild(renderer.domElement);
    // 1、设置渲染器像素比为当前电脑像素比，但是不要超过2，GPU压力会很大
    renderer.setPixelRatio(Math.min[(window.devicePixelRatio, 2)]); //
    function animate() {
      requestAnimationFrame(animate);
      renderer.render(scene, camera);
    }
    animate();

    // 2、窗口自适应
    window.addEventListener('resize', () => {
      // 更新相机宽高比
      camera.aspect = window.innerWidth / window.innerHeight;
      // 更新相机投影矩阵
      camera.updateProjectionMatrix();

      // 更新渲染器尺寸
      renderer.setSize(window.innerWidth, window.innerHeight);
    });

    // 3、全屏
    window.addEventListener('dblclick', () => {
      // 1. 检查全屏状态（兼容写法）
      const isFullscreen =
        document.fullscreenElement ||
        document.webkitFullscreenElement || // Safari/旧Chrome
        document.msFullscreenElement; // IE/Edge

      // 2. 进入全屏
      if (!isFullscreen) {
        const element = mountRef.current;
        if (element) {
          const requestFullscreen =
            element.requestFullscreen ||
            element.webkitRequestFullscreen || // Safari
            element.msRequestFullscreen; // IE/Edge

          if (requestFullscreen) {
            requestFullscreen.call(element).catch((err) => {
              console.error('全屏失败:', err);
            });
          }
        }
      }
      // 3. 退出全屏
      else {
        const exitFullscreen =
          document.exitFullscreen ||
          document.webkitExitFullscreen || // Safari
          document.msExitFullscreen; // IE/Edge

        if (exitFullscreen) {
          exitFullscreen.call(document);
        }
      }
    });
  }, []);

  return (
    <div
      ref={mountRef}
      style={{ width: '100%', height: '100vh' }}
    />
  );
}
